﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PicStore.BLL.Impl;
using PicStore.BLL.Interface;
using PicStore.Model;

namespace PicStore.Web.Lib
{
    public class PictureHelper
    {
        public const string DateFormatString = "yyyyMMdd";
        private string PhisicalPathPrefix
        {
            get
            {
                return HttpContext.Current.Server.MapPath("/");
            }
        }
        private string LogisticPathPrefix
        {
            get
            {
                return "";
            }
        }

        public bool DownloadExcelWithPictures(bool needDownloadPicture, List<PictureInfoForExcel> pictures, out string error,
                                                     out string zipFileUrl)
        {
            TimeSpan tsDateLine = DateTime.Now - (new DateTime(2010, 1, 1));
            string timeString = ((int)tsDateLine.TotalSeconds).ToString();
            string pathFirstPart = HttpRuntime.AppDomainAppPath + ConfigurationManager.AppSettings["DownloadFolder"];
            string pathSecondPart = GetPhysicalSubPath(pathFirstPart, "PictureInfoZip" + timeString);

            bool getZipFileSuccess;
            // 生成临时目录，生成Excel，把pic从服务器上都copy过来，然后连同excel打包成Zip文件。
            // 把zip文件的url发给客户端。
            zipFileUrl = DownloadPictures(timeString, pictures, pathFirstPart, pathSecondPart,
                                                              needDownloadPicture, out getZipFileSuccess, out error);
            return getZipFileSuccess;
        }

        public string DownloadPictures(string timeString, List<PictureInfoForExcel> pictures, string pathFirstPart,
            string pathSecondPart, bool needPicture, out bool getZipFileSuccess, out string error)
        {
            getZipFileSuccess = true;
            error = String.Empty;
            string zipFileUrl = String.Empty;

            string destFilePath = pathFirstPart + pathSecondPart;

            string sourcePicFolder = ConfigurationManager.AppSettings["PicturePhysicalFolder"];
            foreach (var info in pictures)
            {
                string onlyFileName = info.PictureOnlyFileName;
                if (needPicture)
                {
                    // copy file for zip.  if file name is the same then overwrite it.
                    string destFile = String.Format(@"{0}\{1}", destFilePath, info.PictureOnlyFileName);
                    if (string.IsNullOrEmpty(info.PicturePhysicalFullName) == false)
                    {
                        if (File.Exists(info.PicturePhysicalFullName))
                        {
                            File.Copy(info.PicturePhysicalFullName, destFile, true);
                        }
                    }
                }

                // change path name to only file name for download excel.
                info.PicturePhysicalFullName = onlyFileName;
            }

            string zipFilePath = destFilePath + "/" + timeString + ".zip";
            string referror = String.Empty;

            string excelFileName = destFilePath + "/PictureDetailInfo_" + timeString + ".xls";
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);

            DataGrid dgGrid = new DataGrid();
            var dt = ListToDataTable(pictures);
            dgGrid.DataSource = dt;
            dgGrid.HeaderStyle.Font.Bold = true;
            dgGrid.DataBind();
            dgGrid.RenderControl(hw);

            using (StreamWriter sw = new StreamWriter(excelFileName))
            {
                string table = tw.ToString();
                sw.Write(table);
                sw.Flush();
                sw.Close();
            }

            if (FileHelper.PutFilesIntoZip(destFilePath, zipFilePath, out referror))
            {
                zipFileUrl = ConfigurationManager.AppSettings["DownloadFolder"] + pathSecondPart + "/" + timeString + ".zip";
                string delError = String.Empty;
                do
                {
                    FileHelper.DeleteFiles(destFilePath, "jpg", out delError);
                } while (!String.IsNullOrEmpty(delError));
            }
            else
            {
                error = "Zip files failed, error message is:：" + referror; ;
                getZipFileSuccess = false;
            }

            return zipFileUrl;
        }

        public DataTable ListToDataTable(List<PictureInfoForExcel> pictures)
        {
            ICategoryService categoryService = new CategoryService();
            if (pictures == null || pictures.Count < 1) return null;

            DataTable dt = new DataTable();
            int columnCount = ExcelHeader.Headers.Length;
            for (int i = 0; i < columnCount; i++)
            {
                dt.Columns.Add(ExcelHeader.Headers[i]);
            }

            foreach (var pic in pictures)
            {
                // Add every column into the row.
                var row = dt.NewRow();
                row["File NO."] = pic.PictureOnlyFileName;
                row["Year"] = pic.TakePhotoDate.ToString("yyyy");
                row["Month"] = pic.TakePhotoDate.ToString("MM");
                row["Date"] = pic.TakePhotoDate.ToString("dd");
                row["Place"] = pic.Place;
                row["Sex"] = pic.Sex;

                row["Item"] = pic.Item;
                row["Color"] = pic.Color;
                row["Style"] = pic.Style;
                row["Length"] = pic.Length;
                row["Collar"] = pic.Collar;
                row["Front"] = pic.Front;

                row["Sleeve"] = pic.Sleeve;
                row["Sweater Texture"] = pic.SweaterTexture;
                row["Type"] = categoryService.GetItemName((int)BaseCategoryEnum.Type, pic.Type);
                row["PictureId"] = pic.PictureId;

                dt.Rows.Add(row);
            }
            return dt;
        }

        public static string GetPhysicalSubPath(string filePath, string subFolder)
        {
            DeleteOldFolders(filePath);
            DateTime today = DateTime.Now;

            string pathOfToday = String.Format("{0}/{1}/{2}", filePath, today.ToString(DateFormatString), subFolder);
            DirectoryInfo todayFolder = new DirectoryInfo(pathOfToday);
            if (!todayFolder.Exists)
            {
                todayFolder.Create();
            }

            return ("/" + today.ToString(DateFormatString) + "/" + subFolder);
        }

        public static void DeleteOldFolders(string filePath)
        {
            DateTime today = DateTime.Now;
            DirectoryInfo dr = new DirectoryInfo(filePath);
            if (!dr.Exists)
            {
                dr.Create();
            }

            // 删除前天所有的pdf文件
            string pathOfYesterday = String.Format("{0}/{1}", filePath, today.AddDays(-2).ToString(DateFormatString));
            DirectoryInfo yesterdayFolder = new DirectoryInfo(pathOfYesterday);
            if (yesterdayFolder.Exists)
            {
                yesterdayFolder.Delete(true);
            }
        }
    }
}